package com.tlx.pdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.tlx.core.util.TFileUtils;

public class PdfOperateUtils {

    // 合并目录下所有pdf，子目录也能合并
    public static void mergePdfByDirIncludeSon(String dirPath) {
        // 先处理当前目录
        mergePdfByDir(dirPath);

        // 再递归
        List<String> sonDirList = TFileUtils.getDirList(dirPath);
        for (String sonPath : sonDirList) {
            mergePdfByDirIncludeSon(sonPath);
        }
    }

    // 合并一个目录下的pdf，只当前目录，没有子
    public static String mergePdfByDir(String dirPath) {
        List<String> pdfList = TFileUtils.getFileListByExt(dirPath, "pdf");
        if (CollectionUtils.isNotEmpty(pdfList)) {
            String baseName = FilenameUtils.getBaseName(dirPath);
            File lastFile = new File(dirPath, baseName + ".pdf");
            mergePdf(pdfList, lastFile.getAbsolutePath());
            return lastFile.getAbsolutePath();
        }
        return null;
    }

    public static void mergePdf(List<String> filePathList, String savePath) {
        if (filePathList.contains(savePath)) {
            throw new RuntimeException("要合并的pdf中有最终pdf，无法合并");
        }

        OutputStream os = null;
        try {

            if (CollectionUtils.isEmpty(filePathList)) {
                return;
            }

            os = new FileOutputStream(savePath);

            PdfReader pr = new PdfReader(filePathList.get(0));
            Document document = new Document(pr.getPageSize(1));

            PdfCopy copy = new PdfCopy(document, os);

            document.open();

            document.newPage();
            document.add(new Paragraph("A Hello World PDF document."));

            for (String path : filePathList) {

                PdfReader reader = new PdfReader(path);

                int n = reader.getNumberOfPages();

                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
                reader.close();
            }
            pr.close();
            copy.close();
            document.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(os);
        }
    }
}
